package com.zz.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zz.repository.Userrole.Userrole;
import com.zz.repository.user.User;
import com.zz.service.UserService;
import com.zz.service.UserroleService;
import com.zz.utils.Constant;
import com.zz.utils.Encrypt;

@Controller
@RequestMapping("/data/")
public class DataController {
	@Autowired
	private UserService userService;
	@Autowired
	private UserroleService userroleService;

	@RequestMapping(value = "adduser", method = RequestMethod.POST)
	@ResponseBody
	public Object adduser(User userinfo, HttpServletRequest request, HttpServletResponse response) {
		Map<Object, Object> json = new HashMap<Object, Object>();
		json.put("info", userService.addUser(userinfo));
		return json;
	}

	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	public Object login(User userinfo, HttpServletRequest request, HttpServletResponse response, HttpSession session) {
		Map<Object, Object> json = new HashMap<Object, Object>();
		User users = userService.login(userinfo);
		String shaPass = Encrypt.SHA512(userinfo.getPassword());
		if (users == null) {
			json.put("info", "用户不存在");
			json.put("dlu", false);
		} else if (!users.getPassword().equals(shaPass)) {
			json.put("info", "密码错误");
			json.put("dlu", false);
		} else {
			// 登录session操作。
			session.setAttribute(Constant.LOGIN_USER, users);
			// 登录角色session操作。
			List<Userrole> roles = userroleService.getroles(users.getRole());
			session.setAttribute(Constant.LOGIN_USER_ROLE, roles);
			json.put("info", "登录成功");
			json.put("dlu", true);
		}

		return json;
	}

	@RequestMapping(value = "validate", method = RequestMethod.POST)
	@ResponseBody
	public Object validate(User userinfo, @RequestParam(required = false) Integer flg, HttpServletRequest request,
			HttpServletResponse response) {
		return userService.validate(userinfo, flg);
	}
}
